# 导入pptx包
from pptx import Presentation
import os
prs = Presentation(r'.\爬虫实训第一课.pptx')
text_number=0

with open('ppt文本.txt','w',encoding='utf-8-sig')as file:
    # 演示文稿中的幻燈片的對象
    for slide in prs.slides:
        text_number+=1
        file.writelines(['幻灯片{}'.format(text_number),'\n'])
    # 对幻燈片的對象进行遍历同时，获取单个幻燈片中形狀對象实例集合进行遍历
        for shape in slide.shapes:
            try:
                # 获取二进制字符流
                imdata = shape.image.blob
                # 判断文件后缀类型
                imagetype = shape.image.content_type
                typekey = imagetype.find('/') + 1
                imtype = imagetype[typekey:]
                # 创建image文件夹保存抽出图片
                path = "./image/幻灯片{}/".format(text_number)
                if not os.path.exists(path):
                    os.makedirs(path)
                # 图片生成
                image_file = path + shape.name + "." + imtype
                file_str=open(image_file,'wb')
                file_str.write(imdata)
                file_str.close()

            except:
    # 判断形狀對象实例是否包含文本
                if not shape.has_text_frame:
                    continue

    # 遍历该形狀對象，获取文字
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        file.writelines([2*'\t',run.text,'\n'])
    
    